<script setup>
import { ref, onMounted } from 'vue'
import { queryPageApi, deleteApi, updateApi, addApi, queryInfoApi } from '@/api/clazz.js'
import { queryPageApi as queryEmpPageApi } from '@/api/emp.js'
import { ElMessage, ElMessageBox } from 'element-plus'

// 班级列表数据
const classList = ref([])
const total = ref(0) // 总条数

// 搜索表单对象
const searchClass = ref({
  name: '',
  begin: '',
  end: '',
  page: 1,
  pageSize: 10
})

// 控制弹窗显示
const dialogVisible = ref(false)
const dialogTitle = ref('')

// 班主任列表数据（职位为班主任的员工）
const teachers = ref([])

// 当前编辑的班级信息
const currentClass = ref({
  id: null,
  name: '',
  room: '',
  beginDate: '',
  endDate: '',
  masterId: null,
  subject: null
})

// 计算班级状态
const getClassStatus = (beginDate, endDate) => {
  const now = new Date()
  const begin = new Date(beginDate)
  const end = new Date(endDate)
  
  if (now < begin) {
    return '未开课'
  } else if (now > end) {
    return '已结课'
  } else {
    return '在读中'
  }
}

// 搜索方法
const search = async () => {
  try {
    const result = await queryPageApi(
      searchClass.value.name,
      searchClass.value.begin,
      searchClass.value.end,
      searchClass.value.page,
      searchClass.value.pageSize
    )
    classList.value = result.data.rows
    total.value = result.data.total
  } catch (error) {
    console.error('查询失败:', error)
    ElMessage.error('查询失败')
  }
}

// 表单提交
const onSubmit = () => {
  searchClass.value.page = 1
  search()
}

// 分页变化
const handlePageChange = (page) => {
  searchClass.value.page = page
  search()
}

// 查询职位为班主任的员工
const queryTeachers = async () => {
  try {
    const result = await queryEmpPageApi('', 1, '', '', 1, 1000) // 职位1表示班主任
    if (result.code) {
      teachers.value = result.data.rows
    }
  } catch (error) {
    console.error('查询班主任失败:', error)
    ElMessage.error('查询班主任失败')
  }
}

// 新增班级
const handleAdd = () => {
  currentClass.value = {
    id: null,
    name: '',
    room: '',
    beginDate: '',
    endDate: '',
    masterId: null,
    subject: null
  }
  dialogTitle.value = '新增班级'
  dialogVisible.value = true
}

// 编辑班级
const handleEdit = async (id) => {
  try {
    const result = await queryInfoApi(id)
    currentClass.value = { ...result.data }
    dialogTitle.value = '编辑班级'
    dialogVisible.value = true
  } catch (error) {
    console.error('获取班级信息失败:', error)
    ElMessage.error('获取班级信息失败')
  }
}

// 删除班级
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除班级"${row.name}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteApi(row.id)
      ElMessage.success('删除成功')
      search()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  })
}

// 保存班级信息（新增或修改）
const saveClass = async () => {
  try {
    // 验证必填字段
    if (!currentClass.value.name) {
      ElMessage.warning('请输入班级名称')
      return
    }
    if (!currentClass.value.room) {
      ElMessage.warning('请输入教室')
      return
    }
    if (!currentClass.value.beginDate) {
      ElMessage.warning('请选择开班时间')
      return
    }
    if (!currentClass.value.endDate) {
      ElMessage.warning('请选择结课时间')
      return
    }
    if (!currentClass.value.masterId) {
      ElMessage.warning('请选择班主任')
      return
    }

    // 保存数据
    let result;
    if (currentClass.value.id) {
      // 修改班级
      result = await updateApi(currentClass.value)
    } else {
      // 新增班级
      result = await addApi(currentClass.value)
    }
    
    if (result.code) {
      ElMessage.success(currentClass.value.id ? '修改成功' : '新增成功')
      dialogVisible.value = false
      search()
    } else {
      ElMessage.error(result.msg || '操作失败')
    }
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败: ' + (error.message || '未知错误'))
  }
}

// 组件挂载后执行查询
onMounted(() => {
  search()
  queryTeachers()
})

// 清除搜索条件
const clearSearch = () => {
  searchClass.value.name = ''
  searchClass.value.begin = ''
  searchClass.value.end = ''
  searchClass.value.page = 1
  search()
}
</script>

<template>
  <el-form :inline="true" :model="searchClass" class="demo-form-inline" label-width="80px">
    <el-form-item label="班级名称">
      <el-input v-model="searchClass.name" placeholder="请输入班级名称" clearable />
    </el-form-item>

    <el-form-item label="开班时间">
      <el-date-picker
        v-model="searchClass.begin"
        type="date"
        placeholder="请选择开班时间"
        clearable
        value-format="YYYY-MM-DD"
      />
    </el-form-item>
    
    <el-form-item label="结课时间">
      <el-date-picker
        v-model="searchClass.end"
        type="date"
        placeholder="请选择结课时间"
        clearable
        value-format="YYYY-MM-DD"
      />
    </el-form-item>
    
    <el-form-item>
      <el-button type="primary" @click="onSubmit">查询</el-button>
      <el-button @click="clearSearch">清除</el-button>
      <el-button type="success" @click="handleAdd">新增班级</el-button>
    </el-form-item>
  </el-form>

  <!-- 班级列表 -->
  <el-table :data="classList" style="width: 100%" border>
    <el-table-column prop="name" label="班级名称" min-width="120" />
    <el-table-column prop="room" label="教室" />
    <el-table-column prop="beginDate" label="开班时间" width="120" />
    <el-table-column prop="endDate" label="结课时间" width="120" />
    <el-table-column prop="masterName" label="班主任" />
    <el-table-column label="状态">
      <template #default="scope">
        <el-tag :type="getClassStatus(scope.row.beginDate, scope.row.endDate) === '在读中' ? 'success' : 
                  getClassStatus(scope.row.beginDate, scope.row.endDate) === '已结课' ? 'info' : 'warning'">
          {{ getClassStatus(scope.row.beginDate, scope.row.endDate) }}
        </el-tag>
      </template>
    </el-table-column>
    <el-table-column label="操作" width="150" fixed="right">
      <template #default="scope">
        <el-button @click="handleEdit(scope.row.id)" type="primary" size="small">编辑</el-button>
        <el-button @click="handleDelete(scope.row)" type="danger" size="small">删除</el-button>
      </template>
    </el-table-column>
  </el-table>

  <!-- 分页 -->
  <el-pagination
    @current-change="handlePageChange"
    :current-page="searchClass.page"
    :page-size="searchClass.pageSize"
    :total="total"
    layout="total, prev, pager, next, jumper"
    background
    style="margin-top: 20px; text-align: center;"
  />

  <!-- 编辑/新增弹窗 -->
  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px">
    <el-form :model="currentClass" label-width="80px">
      <el-form-item label="班级名称">
        <el-input v-model="currentClass.name" placeholder="请输入班级名称" />
      </el-form-item>
      <el-form-item label="教室">
        <el-input v-model="currentClass.room" placeholder="请输入教室" />
      </el-form-item>
      <el-form-item label="开班时间">
        <el-date-picker 
          v-model="currentClass.beginDate" 
          type="date" 
          value-format="YYYY-MM-DD"
          placeholder="请选择开班时间"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="结课时间">
        <el-date-picker 
          v-model="currentClass.endDate" 
          type="date" 
          value-format="YYYY-MM-DD"
          placeholder="请选择结课时间"
          style="width: 100%"
        />
      </el-form-item>
      <el-form-item label="班主任">
        <el-select v-model="currentClass.masterId" style="width: 100%" placeholder="请选择班主任">
          <el-option 
            v-for="teacher in teachers" 
            :key="teacher.id" 
            :label="teacher.name" 
            :value="teacher.id" 
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveClass">保存</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
.demo-form-inline {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f5f5;
  border-radius: 4px;
}
</style>